package net.dreamlu.assets.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PathKit;

/**
 * 配置添加路径判断区分绝对路径、相对路径、classpath、webjars。
 * 
 * 绝对路径    c://xxx/xxx
 * 相对路径    static/xxx/xx
 * classpath classpath:net/dreamlu/assets/test.js
 * webjars   webjars:/webjars/jquery/3.1.1-1/jquery.min.js
 * http https
 * 
 * @author L.cm
 * email:596392912@qq.com
 * site:http://www.dreamlu.net
 * date:2017年3月22日下午8:32:08
 */
public class ResourceUtils {
	// 字符集utf-8
	private static final Charset UTF_8 = Charset.forName("UTF-8");
	private static final String HTTP_REGEX = "^https?://.+$";
	
	private static String getByWebjars(String webjarPath) throws IOException {
		String webjarsResourceURI = "/META-INF/resources" + webjarPath;
		return getByClassPath(webjarsResourceURI);
	}
	
	private static String getByClassPath(String classPathURI) throws IOException {
		InputStream input = ResourceUtils.class.getResourceAsStream(classPathURI);
		try {
			return IOUtils.toString(input, UTF_8);
		} finally {
			IOUtils.closeQuietly(input);
		}
	}
	
	private static String getByHttp(String url) {
		return HttpKit.get(url);
	}
	
	/**
	 * 读取js，css文件
	 * @param path 路径
	 * @return 文件内容
	 * @throws IOException io异常
	 */
	public static String getResource(String path) throws IOException {
		if (path.startsWith("webjars:")) {
			String webJarPath = repairPath(path.substring(8, path.length()));
			return getByWebjars(webJarPath);
		} else if (path.startsWith("classpath:")) {
			String classpath = repairPath(path.substring(10, path.length()));
			return getByClassPath(classpath);
		} else if (path.matches(HTTP_REGEX)) {
			return getByHttp(path);
		} else if (PathKit.isAbsolutelyPath(path)) {
			return FileUtils.readFileToString(new File(path), UTF_8);
		} else {
			String webRoot = PathKit.getWebRootPath();
			String filePath = webRoot + File.separator + path;
			return FileUtils.readFileToString(new File(filePath), UTF_8);
		}
	}
	
	/**
	 * 路径修复
	 * @param path
	 * @return
	 */
	private static String repairPath(String path) {
		if (!path.startsWith("/")) {
			path = "/" + path;
		}
		return path;
	}
	
}
